const cloud = require('wx-server-sdk');

// 初始化云开发
cloud.init({
  env: 'cloud1-6g22e569b6b129d5'
});

const db = cloud.database();
const _ = db.command;

// 验证token
async function validateToken(token) {
  if (!token) {
    return {
      valid: false,
      message: '缺少访问令牌'
    }
  }

  try {
    const tokenResult = await db.collection('user_tokens')
      .where({
        token: token,
        expireTime: _.gt(new Date())
      })
      .get()

    if (tokenResult.data.length === 0) {
      return {
        valid: false,
        message: '访问令牌无效或已过期'
      }
    }

    return {
      valid: true,
      userId: tokenResult.data[0].userId
    }
  } catch (error) {
    console.error('验证token失败:', error)
    return {
      valid: false,
      message: '验证失败'
    }
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { action, data, token } = event

  switch (action) {
    case 'getPoints':
      return await getPoints(data, token)
    case 'addPoints':
      return await addPoints(data, token)
    case 'consumePoints':
      return await consumePoints(data, token)
    case 'getPointsHistory':
      return await getPointsHistory(data, token)
    default:
      return {
        success: false,
        code: 400,
        message: '未知操作'
      }
  }
}

// 获取用户积分
async function getPoints(data, token) {
  // 验证token
  const tokenValidation = await validateToken(token)
  if (!tokenValidation.valid) {
    return {
      success: false,
      code: 401,
      message: tokenValidation.message
    }
  }

  try {
    const userResult = await db.collection('users').doc(tokenValidation.userId).get()
    
    if (!userResult.data) {
      return {
        success: false,
        code: 404,
        message: '用户不存在'
      }
    }

    return {
      success: true,
      code: 200,
      message: '获取积分成功',
      data: {
        points: userResult.data.points || 0,
        userId: tokenValidation.userId
      }
    }
  } catch (error) {
    console.error('获取积分失败:', error)
    return {
      success: false,
      code: 500,
      message: '获取积分失败'
    }
  }
}

// 充值积分（管理员功能）
async function addPoints(data, token) {
  const { userId, points, reason } = data

  // 验证token
  const tokenValidation = await validateToken(token)
  if (!tokenValidation.valid) {
    return {
      success: false,
      code: 401,
      message: tokenValidation.message
    }
  }

  // 验证参数
  if (!userId || !points || points <= 0) {
    return {
      success: false,
      code: 400,
      message: '参数错误'
    }
  }

  try {
    // 检查操作者权限（可以扩展为管理员权限检查）
    const operatorResult = await db.collection('users').doc(tokenValidation.userId).get()
    if (!operatorResult.data || operatorResult.data.role !== 'admin') {
      return {
        success: false,
        code: 403,
        message: '无权限操作'
      }
    }

    // 给用户增加积分
    await db.collection('users').doc(userId).update({
      data: {
        points: _.inc(points)
      }
    })

    // 记录积分变动历史
    await db.collection('points_history').add({
      data: {
        userId: userId,
        points: points,
        type: 'recharge',
        reason: reason || '管理员充值',
        operatorId: tokenValidation.userId,
        createTime: new Date()
      }
    })

    return {
      success: true,
      code: 200,
      message: '充值成功'
    }
  } catch (error) {
    console.error('充值积分失败:', error)
    return {
      success: false,
      code: 500,
      message: '充值失败'
    }
  }
}

// 消费积分
async function consumePoints(data, token) {
  const { points, reason } = data

  // 验证token
  const tokenValidation = await validateToken(token)
  if (!tokenValidation.valid) {
    return {
      success: false,
      code: 401,
      message: tokenValidation.message
    }
  }

  // 验证参数
  if (!points || points <= 0) {
    return {
      success: false,
      code: 400,
      message: '参数错误'
    }
  }

  try {
    // 获取用户当前积分
    const userResult = await db.collection('users').doc(tokenValidation.userId).get()
    if (!userResult.data) {
      return {
        success: false,
        code: 404,
        message: '用户不存在'
      }
    }

    const currentPoints = userResult.data.points || 0
    if (currentPoints < points) {
      return {
        success: false,
        code: 403,
        message: `积分不足，需要${points}积分，当前有${currentPoints}积分`
      }
    }

    // 扣除积分
    await db.collection('users').doc(tokenValidation.userId).update({
      data: {
        points: _.inc(-points)
      }
    })

    // 记录积分变动历史
    await db.collection('points_history').add({
      data: {
        userId: tokenValidation.userId,
        points: -points,
        type: 'consume',
        reason: reason || '消费',
        createTime: new Date()
      }
    })

    return {
      success: true,
      code: 200,
      message: '消费成功',
      data: {
        remainingPoints: currentPoints - points
      }
    }
  } catch (error) {
    console.error('消费积分失败:', error)
    return {
      success: false,
      code: 500,
      message: '消费失败'
    }
  }
}

// 获取积分变动历史
async function getPointsHistory(data, token) {
  const { page = 1, limit = 20 } = data

  // 验证token
  const tokenValidation = await validateToken(token)
  if (!tokenValidation.valid) {
    return {
      success: false,
      code: 401,
      message: tokenValidation.message
    }
  }

  try {
    const skip = (page - 1) * limit
    
    const result = await db.collection('points_history')
      .where({
        userId: tokenValidation.userId
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get()

    return {
      success: true,
      code: 200,
      message: '获取历史记录成功',
      data: {
        list: result.data,
        page: page,
        limit: limit,
        total: result.data.length
      }
    }
  } catch (error) {
    console.error('获取积分历史失败:', error)
    return {
      success: false,
      code: 500,
      message: '获取历史记录失败'
    }
  }
} 